import React, {Component} from 'react';
import {observer, inject} from 'mobx-react';
import * as mobx from 'mobx';
import cloneDeep from 'lodash/cloneDeep';
import {Tree, Modal, message, Button} from 'antd';
import {WeaTreeNew, WeaLocaleProvider} from 'ecCom';
import {stopEvent, getInputKeys} from '../../util/TreeUtil';
import '../../style/tree.less';

const getLabel = WeaLocaleProvider.getLabel;
const TreeNode = Tree.TreeNode;
const confirm = Modal.confirm;

@inject('favouriteDirStore')
@observer
class FavDirTree extends Component {
    constructor(props) {
        super(props);
        this.state = {
            newTreeData: false,
        };
    }

    componentDidMount() {
        const {favouriteDirStore} = this.props;
        favouriteDirStore.getObjTree(this);
    }

    getTreeInstance = tree => {
        this.tree = tree;
    }

    asyncLoad = (item) => {
        const nodeid = item.nodeid;
        const {favouriteDirStore} = this.props;

        function fn() {
            return new Promise((resolve, reject) => {
                resolve(favouriteDirStore.loadTreedata(nodeid)); // 这是一个异步函数
            });
        }

        const fn_1 = async function () {
            await fn();// 等待异步操作执行完了后执行的方法
            return new Promise((resolve) => { // loadData接口需要一个promise对象，所以这里要包装返回一个promise对象
                const data = {
                    datas: favouriteDirStore.loadedTreeData,
                };
                resolve(data);
            });
        };
        return fn_1();
    }
    findParentId = (data) => {
        const arr = data.split('__');
        const fatherid = arr[arr.length - 2].split('-')[arr.length == 2 ? 0 : 1];
        return fatherid;
    }
    // 设置父节点的删除符号
    setOPS = (data, target, mode) => {
        let hasChildFlag = false;
        data.map((val) => {
            if (val.children) {
                const s = val.children;
                this.setOPS(s, target);
            }
            if (val.nodeid == target) {
                val.children.map((value) => {
                    const c = 'deleted' in value;
                    if (c == false) {
                        hasChildFlag = true;
                    }
                });
                if (hasChildFlag == true) {
                    val.ops[2].type = '';
                } else {
                    val.ops[2].type = 'delete';
                }
            }
        });
        // this.props.favouriteDirStore.initTreeData = data;
        this.props.favouriteDirStore.setInitTreeData(data);
        this.setState({newTreeData: true});
    }

    setOpts = (data) => {
        const toggleDeleteOp = (item, show = false) => {
            if (item.ops && item.ops.length >= 2) {
                if (show) {
                    item.ops[2].type = 'delete';
                } else {
                    item.ops[2].type = '';
                }
            }
        }

        const loop = (datas) => {
            datas.map(item => {
                if (item.children && item.children.length > 0) {
                    let hasChild = false;
                    hasChild = item.children.some(ele => {
                        const {deleted = false} = ele;      //判断节点是否是已删除的
                        return deleted !== true;
                    });

                    if (hasChild) {
                        //有子节点，不显示删除的按钮
                        toggleDeleteOp(item);
                        loop(item.children);
                    } else {
                        toggleDeleteOp(item, true);
                    }
                } else {        //没有子节点，显示删除的按钮
                    if (!item.isParent) {      //虽然没有子节点，但是有可能异步树的节点没有加载
                        toggleDeleteOp(item, true);
                    }
                }
            })
        }

        const {favouriteDirStore} = this.props;

        loop(data);
        data = mobx.toJS(data);
        favouriteDirStore.setInitTreeData(data);
        this.setState({newTreeData: true});

        const btnDisable = data.some(item => {
            const {isRoot = false, displayType = '', deleted = false} = item;

            return isRoot && 'add' === displayType && !deleted;     //根节点中有正在添加的
        });
        favouriteDirStore.controlBtnDisable(btnDisable);        //控制添加根目录的按钮是否可用
    }


    dragSet = (dragNode, targetNode, datas) => {
        datas.map((val) => {
            if (val.children) {
                if (val.ops && val.ops.length >= 2) {
                    if (val.children.length == 0) {
                        val.ops[2].type = 'delete';
                        val.icon = '';
                    } else {
                        val.ops[2].type = '';
                    }
                }
                const s = val.children;
                this.dragSet(dragNode, targetNode, s);
            }
        });
        /* this.props.favouriteDirStore.initTreeData = datas
          this.setState({newTreeData: true}) */
    }
    // 找父节点id
    testFind = (node, treeData, mode) => {
        if (node.parentTreeKey) {
            const FID = this.findParentId(node.parentTreeKey);
            this.setOPS(treeData, FID, mode);
        }
    }

    onDragNode = (dragNode, targetNode, datas) => {
        const {favouriteDirStore} = this.props;
        const {initTreeData} = favouriteDirStore;
        const oldData = cloneDeep(mobx.toJS(initTreeData));
        const newData = cloneDeep(datas);
        const dnode = cloneDeep(dragNode);
        const tnode = cloneDeep(targetNode);

        this.dragSet(dnode, tnode, newData);
        favouriteDirStore.setInitTreeData(newData);
        // 说明是“我的收藏”目录，该目录不允许拖拽，也不允许添加子节点
        if (tnode.nodeid != '-1' && dnode.nodeid != '-1') {
            favouriteDirStore.saveDragNode(dnode, tnode, newData);
        } else {
            window.setTimeout(() => {
                favouriteDirStore.setInitTreeData(oldData);
                this.dragSet(dnode, tnode, oldData);
            }, 1000);
        }
        this.setState({newTreeData: true});
    }

    onDatasChange = datas => {
        const {favouriteDirStore} = this.props;
        window.treeData = datas;
        //favouriteDirStore.setInitTreeData(mobx.toJS(datas));
        window.setTimeout(() => {
            this.setOpts(datas);
        }, 300)
    }

    onSelect = (ids, nodeids, nodes, event) => {
        const {onSelect} = this.props;
        onSelect && onSelect(nodeids[0]);
    }

    onAdd = (value, node) => {
        const {favouriteDirStore} = this.props;
        //this.setOPS(window.treeData, node == undefined ? '0' : node.nodeid, 'add');
        return favouriteDirStore.addDirectory(node == undefined ? '0' : node.nodeid, value);
    }

    onEdit = (value, node) => {
        const {favouriteDirStore} = this.props;
        return favouriteDirStore.editDirectory(value, node);
    }

    onDelete = node => {
        const that = this;
        const {favouriteDirStore} = this.props;
        favouriteDirStore.deleteNode(node.nodeid, () => {
            this.props.onSelect('-1');      //删除了节点后，默认加载“我的收藏”目录的数据
        });
        /* setTimeout(() => {
             that.testFind(node, window.treeData, 'delete');
         }, 0);*/
    }

    render() {
        const {favouriteDirStore, onSelect} = this.props;
        const {initTreeData} = favouriteDirStore;
        const treeData = cloneDeep(mobx.toJS(initTreeData));
        return (
            <WeaTreeNew
                ecId={`${this && this.props && this.props.ecId || ''}_WeaTreeNew@l6kukt`}
                ref={this.getTreeInstance}
                draggable
                // addToLast
                // hasRadio={true}
                // radioCheckedKey={483}
                // onRadioCheck={(radioCheckedKey) => { console.log(radioCheckedKey) }}
                selectedKeys={this.props.favouriteDirStore.selectedKey}
                deleteConfirmText={getLabel('501373', '删除目录，该目录下的收藏将自动移至默认目录"我的收藏"。确定要删除吗？')}
                defaultParentIcon={'icon-coms-LargeArea'}
                onDatasChange={this.onDatasChange}
                onSelect={this.onSelect}
                datas={treeData}
                loadData={this.asyncLoad}
                onAdd={this.onAdd}
                onEdit={this.onEdit}
                onDelete={this.onDelete}
                onDrag={this.onDragNode}
            >
                {this.state.newTreeData}
            </WeaTreeNew>);
    }
}

FavDirTree.PropTypes = {
    onSelect: React.PropTypes.func.isRequired,
    hasRadio: React.PropTypes.bool,
};

export default FavDirTree;
